package com.Util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.template.EasyReadTemplate;
import com.template.EasyWriterTemplate;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Accessors(chain = true)
public class EasyOutUtil {
    /*
    用于模版操作处理
    */
    private EasyReadTemplate readTemplate=null;
    private EasyWriterTemplate writerTemplate=null;
    private List<String> fileNames=null;
    private String outFileName=null;
    private ExcelWriter excelWriter=null;
    private  List<Map<Integer, String>> errorlist=null;
    private  List<Map<Integer, String>> headlist=null;

    private int SIZE=0;
    public  int  getFileSize(){
        if (null!=fileNames&&null!=errorlist)
        return fileNames.size()-errorlist.size();
        if (null!=fileNames)
        return fileNames.size();
        return 0;
    }
    public int getDataSize(){
        return SIZE;
    }
    public String getErrorList(){

        StringBuffer buffer=new StringBuffer();
        if (null!=errorlist){
        for (Map<Integer, String> integerStringMap : errorlist) {
           buffer.append(integerStringMap.get(0)+" , ");
        }}else {
            return "无";
        }
        return buffer.toString();
    }
    public void  outStart(){
        if (null!=readTemplate&&null!=writerTemplate&&null!=fileNames&&null!=outFileName){
            /*
            文件读取
            */
            try {
                excelWriter=EasyExcel.write(outFileName).build();
                int i=0;
                for (String fileName : fileNames) {
                    readOne(fileName,i);
                    i++;
                }
            } catch (Exception e) {
                System.out.println("文件输出出现错误：可能是excel字段过大,或者目标正在被使用");
                e.printStackTrace();
            }finally {
                  excelWriter.finish();//流关闭
                excelWriter=null;
            }

        }
    }
    private void read(String filename,int index){

        /*
         写成多个sheet
        */
        try {
            EasyExcel.read(filename, readTemplate).sheet().doRead();
        Thread.sleep(200);
            List<Map<Integer, String>> list = readTemplate.getList();
         WriteSheet writeSheet = EasyExcel.writerSheet(index+1,fileNameSplit(filename)).head(writerTemplate.head(list)).build();//doWriter就是静态打包，不能单个写
            writer(writerTemplate.dataList(list),writeSheet);//写入
        } catch (Exception e) {

            System.out.printf("文件读取出现错误，异常已屏蔽，如需查看请注析下行，当前文件为:%s%n请在程序结束后自行添加%n",filename);
            e.printStackTrace();
        }

    }
    private void readOne(String filename,int index){

        /*
         写成单个sheet
        */
        try {
            EasyExcel.read(filename, readTemplate).sheet().doRead();
            Thread.sleep(200);
            List<Map<Integer, String>> list = readTemplate.getList();
            SIZE+=list.size();
            WriteSheet writeSheet=null;

//                 writeSheet = EasyExcel.writerSheet("合并").head(writerTemplate.head(list)).build();//doWriter就是静态打包，不能单个写

                 writeSheet = EasyExcel.writerSheet("合并").build();//doWriter就是静态打包，不能单个写

            writer(writerTemplate.dataList(list),writeSheet);//写入
            if (index==fileNames.size()-1) {
                /*
                如果存在错误，就写出错误sheet
                */
                if (null!=errorlist) {
                    WriteSheet writeSheet1 = EasyExcel.writerSheet("处理信息").head(writerTemplate.head(headlist)).build();
                    writer(writerTemplate.dataList(errorlist), writeSheet1);//写入
                    System.out.printf("总数据条数:%s%n",SIZE);
                }
            }
        } catch (Exception e) {
            System.out.printf("文件读取出现错误,请在处理信息查看%n",filename);

               if (null==errorlist){
                   errorlist=new ArrayList<>();
                   System.out.println("not null");
                    headlist=new ArrayList<>();
                   Map head=new HashMap();
                 head.put(0,"以下文件合并失败,请手动合并");
                   headlist.add(head);
               }
                 Map map=new HashMap();
                 map.put(0,fileNameSplit(filename));
            errorlist.add(map);
            if (index==fileNames.size()-1) {
                /*
                如果存在错误，就写出错误sheet
                */
                if (null!=errorlist) {
                    WriteSheet writeSheet1 = EasyExcel.writerSheet("处理信息").head(writerTemplate.head(headlist)).build();
                    writer(writerTemplate.dataList(errorlist), writeSheet1);//写入
                    System.out.printf("总条数:%s%n",SIZE);
                }
            }
               }

    }
    private void writer(List<List<Object>> data, WriteSheet writeSheet){

        try {
            excelWriter.write(data,writeSheet);
        } catch (Exception e) {

            e.printStackTrace();
        }finally {
            //实例化数据
            readTemplate.initList();
        }


    }
    /*
    文件名解析
    */
    public static String fileNameSplit(String name){
        char[] chars = name.toCharArray();
        boolean TAIl=false;
        int [] size=new int[2];
        for (int i=chars.length-1;i>0;i--){
                if (0!=size[1]){
                    break ;
                }
            switch (chars[i]){
                case '/':

                    if (!TAIl){
                        TAIl=true;
                        size[0]=i;

                    }
                    break;
                default:
                    break;
            }
        }
        String a=name.substring(size[0]+1,chars.length);
    return a;
    }

}
